//
//  ScanDeviceVM.swift
//  Kosspot
//
//  Created by 胡辉 on 2025/7/13.
//

import RxSwift
import Combine
import ToastUI
import SwiftUI
import UTEBluetoothRYApi

class ScanDeviceVM: ObservableObject {
    @Published var animationFlag = 0
    
    @Published var bleManager: UTEBluetoothMgr = UTEBluetoothMgr.sharedInstance()
    
    @Published var isScanning: Bool = false
    @Published var loading: Bool = false
    @Published var pairedDevice: UTEModelDevice = UTEModelDevice()
    @Published var devices: [UTEModelDevice] = []
    
    let appState: AppState
    
    init(appState: AppState) {
        self.appState = appState
        setupDeviceDiscoveryHandler()
        bleManager.mgrDevice.accountTool.onNotifySelect() { result, uteDict in
            if result == 0 {
                // 恢复出厂
            } else if result == 1 {
                //取消配对
            }
        }
        
        bleManager.mgrDevice.onNotifyPair() { pair in
            DispatchQueue.main.async {
                self.loading = false
                if pair == true {
                    //用户确认配对或连接成功
                    let currentDevice: UTEModelDevice = self.bleManager.connnectModel
                    self.pairedDevice = currentDevice
                    let lastDevice = DeviceInfo(from: currentDevice)
                    DeviceManager.shared.setLastConnectedDevice(lastDevice)
                } else {
                    //取消配对
                }
            }
        }
        
    }
    
    func scanDevice() {
        isScanning = true
        self.devices.removeAll()
        bleManager.startScanDevices()
        DispatchQueue.main.asyncAfter(deadline: .now() + 15) {
            self.stopScanDevice()
        }
    }
    
    func stopScanDevice() {
        isScanning = false
        animationFlag += 1
        bleManager.stopScanDevices()
    }
    
    func connectDevice(device: UTEModelDevice) {
        appState.isLoading = true
        stopScanDevice()
        bleManager.connect(device)
    }
    
    private func setupDeviceDiscoveryHandler() {
        appState.bleDelegate.onDeviceDiscovered = { [weak self] newDevice in
            guard let self = self else { return }
            if !self.devices.contains(where: { $0.advertisementAddress == newDevice.advertisementAddress }) {
                self.devices.append(newDevice)
            }
        }
    }
    
}

